package servlet; /**
 * @description:
 * @author: hank
 * @create: 2021-05-17 08:30
 **/

import DBC.DatabaseConnection;
import Factory.DAOFactory;
import domain.Events;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/AddEventsServlet")
public class AddEventsServlet extends HttpServlet {
    private final DatabaseConnection dbc = new DatabaseConnection();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
        response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        response.setHeader("Content-Type","text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String user = request.getParameter("user");
        String week = request.getParameter("week");
        String eventName = request.getParameter("eventName");
        String startTime = request.getParameter("startTime");
        String lastTime = request.getParameter("lastTime");
        String room = request.getParameter("room");
        String detail = request.getParameter("detail");
        int eventID = 0;
        Map<String, Object> map = new HashMap<>();
        try {
            if(DAOFactory.getDataInstance(this.dbc.getConn()).getEvents(user)!=null) {
                eventID = DAOFactory.getDataInstance(this.dbc.getConn()).getEvents(user).get(0).getEventsID()+1;
            }
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        try {
            DAOFactory.SaveDataInstance(this.dbc.getConn()).saveEvents(eventName, eventID, startTime, lastTime, user, week, room, detail);
            map.put("StateCode", 200);
        } catch (Exception e) {
            map.put("StateCode", 500);
            e.printStackTrace();
        }finally {
            response.getWriter().print(com.alibaba.fastjson.JSONObject.toJSONString(map));
        }
    }
}
